package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"knowledge/models/mysqlinit"
	"knowledge/models/redisinit"
	"time"

	"knowledge/knowledgerpc/internal/svc"
	"knowledge/knowledgerpc/knowledgerpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListKnowledgeLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListKnowledgeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListKnowledgeLogic {
	return &ListKnowledgeLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListKnowledgeLogic) ListKnowledge(in *knowledgerpc.ListKnowledgeRequest) (*knowledgerpc.ListKnowledgeResponse, error) {
	// todo: add your logic here and delete this line
	var list []mysqlinit.Knowledge

	get := redisinit.Client.Get("Knowledgerpc")
	if get.Val() == "" {
		mysqlinit.DB.Debug().Find(&list)
		jsonRbyte, _ := json.Marshal(&list)
		redisinit.Client.Set("Knowledgerpc", jsonRbyte, time.Minute*30)
		fmt.Println("mysql")
	} else {
		json.Unmarshal([]byte(get.Val()), &list)
		fmt.Println("redis")
	}

	var Lists []*knowledgerpc.List
	for _, i := range list {
		k := knowledgerpc.List{
			Id:    int64(i.ID),
			Title: i.Title,
			Click: int64(i.Click),
			State: i.State,
		}
		Lists = append(Lists, &k)
	}

	return &knowledgerpc.ListKnowledgeResponse{
		Lists: Lists,
	}, nil
}
